package com.inno.launcher.widget;

import static android.widget.Toast.LENGTH_SHORT;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.inno.launcher.MyApp;
import com.inno.launcher.R;

import java.lang.reflect.Field;

/**
 *
 */

public class CustomToast {
    public static final int   TOAST_TYPE_SUCCESS = 0;
    public static final int   TOAST_TYPE_ERROR   = 1;
    public static final int   TOAST_TYPE_WARNING = 2;
    private static      Toast mToast;

    public static void showToast(CharSequence text) {
        showToast(MyApp.getContext(), text, false);
    }

    public static void showToast(Context context, CharSequence text, boolean showImage) {
        showToast(context, text, LENGTH_SHORT, showImage, -1);
    }
    public static void showToast(Context context, CharSequence text, boolean showImage, int imageResources) {
        showToast(context, text, LENGTH_SHORT, showImage, imageResources);
    }

    public static void showToast(Context context, CharSequence text, int duration, boolean showImage, int imageResources) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        if (mToast == null) {
            mToast = new Toast(context);
        } else {
            mToast.cancel();
            mToast = new Toast(context);
        }
        //获取LayoutInflater对象
        LayoutInflater inflater      = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View           view          = inflater.inflate(R.layout.toast_xml, null);
        TextView       toastTextView = view.findViewById(R.id.message);
        ImageView      imageIv       = view.findViewById(R.id.image_iv);
        if (showImage) {
            imageIv.setVisibility(View.VISIBLE);
            if(imageResources!=-1){
                imageIv.setImageResource(imageResources);
            }
            mToast.setGravity(Gravity.CENTER, 0, 0);
        } else {
            imageIv.setVisibility(View.GONE);
            mToast.setGravity(Gravity.BOTTOM, 0, 160);
        }
        //设置TextView的宽度为 屏幕宽度
        toastTextView.setText(text);

        mToast.setView(view);
        mToast.setDuration(duration);
        mToast.show();
    }


    /**
     * 反射字段
     *
     * @param object    要反射的对象
     * @param fieldName 要反射的字段名称
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private static Object getField(Object object, String fieldName)
            throws NoSuchFieldException, IllegalAccessException {
        Field field = object.getClass().getDeclaredField(fieldName);
        if (field != null) {
            field.setAccessible(true);
            return field.get(object);
        }
        return null;
    }
}
